package interfaces

import (
	"deploy/interfaces/db"
	"deploy/schema"
	"deploy/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"strings"
	"time"
)

func (s *Server)GetConfFromAgent(c *gin.Context){
	result := schema.Result{}
	resultData := schema.SchemaGetAgentConf{}
	defer func() {
		if err := recover(); err != nil {
			if result.Code==0{
				result.Code = 400
			}
			result.Err = fmt.Sprintf("%s",err)
		}
		result.Data=resultData
		log.Println(resultData)
		c.JSON(result.Code,result)
	}()
	// 2 arg
	req := schema.SchemaGetAgentConf{}
	err := c.BindJSON(&req)
	if err != nil {
		log.Println(err.Error())
		panic("参数错误")
	}
	if len(req.UnitIds) == 0{
		panic("请求参数中配置信息不能为空")
	}
	if len(req.UnitIds) >20{
		panic("请求实例数量超过限制")
	}
	// 3、
	pData:=make(chan schema.AgentConf ,len(req.UnitIds))
	for _,i := range req.UnitIds{
		//log.Println(instance)
		go func(instance schema.AgentConf) {
			instanceData := schema.AgentConf{Hostname: instance.Hostname}
			host := schema.GetHostname(instance.Hostname)
			log.Printf("获取实例%s配置%v\n",host,instance.ConfList)
			client := s.FindAClientByNameFromServer(host)
			if client == nil {
				//panic("未找到主机")
				errMsg := fmt.Sprintf("没有找到实例:%s",host)
				log.Println(errMsg)
				instanceData.ErrMsg=errMsg
			} else {
				msg := utils.NewMessage2("12345678", 10, &instance)
				log.Println(string(msg))
				// 发送请求
				client.outChan <- msg

				// 返回数据
				r := <-client.SyncChan
				//log.Println("收到agent的数据", r)
				cr, ok := r.(schema.AgentConf)
				if ok {
					instanceData = cr
				} else {
					instanceData.ErrMsg = "agent配置处理异常"
				}
			}
			// 把每个实例的配置加入进来
			pData <- instanceData
			log.Println(resultData)
		}(i)
	}
	// 处理返回数据
	for i := 0; i < len(req.UnitIds); i++{
		d := <- pData
		resultData.UnitIds = append(resultData.UnitIds, d)
	}
	close(pData)
	//log.Printf("查看agent日志")
	result.Code=200
	result.Msg="查看agent配置文件成功"
	return

}

// 通过配置中心触发的配置更新
func (s *Server)PostReportConfUpdate(c *gin.Context){
	//
	result := schema.Result{}
	defer func() {
		if err := recover(); err != nil {
			if result.Code==0{
				result.Code = 400
			}
			result.Err = fmt.Sprintf("%s",err)
		}
		c.JSON(result.Code,result)
	}()
	// 2 arg
	req := schema.SchemaDingDong{}
	err := c.BindJSON(&req)
	if err != nil {
		log.Println(err.Error())
		panic("参数错误")
	}
	// 2 对比instance是否全部注册成功
	instances := []string{}
	service := ""
	for _,i:=range req.UnitIds{
		hostName := schema.GetHostname(i)
		if hostName !="" {
			instances = append(instances, hostName)
		}
		service = schema.GetService(i)
	}

	log.Println(instances)
	if len(instances) < 1{
		result.Data=instances
		result.Code=404
		return
	}


	rc,nrs:=s.FindClientByNameFromServer(instances)
	if  len(nrs) != 0{
		msg := fmt.Sprintf("主机 %s 未在server中注册",req.UnitIds)
		log.Println(msg,nrs)
		panic(msg)
	}
	log.Println("执行部署 2、实例验证成功，所有的实例都已经注册,count:", len(rc))

	//var cmds utils.Commands
	//dataServer,_ := utils.GetDataConfiguration(service)
	//utils.UpdateConfRestartCommands(&cmds,dataServer)
	//// 对命令进行排序
	//sort.Sort(cmds)

	log.Println("执行部署 3、job转换为任务指令完成", len(rc))
	restart := []string{"ServerStop","ServerStart","WriteConf"}
	// 写数据库
	js := db.JobStatus{
		Status: utils.Running.Str(),
		ServerName: service,
		User: "root",
		Description: "配置中心更新",
		StartTime:time.Now(),
		GroupInstances: utils.SliceToStr(instances,0),
		InstanceType: "",
		InstanceCount: len(instances),
		JobDefinition: strings.Join(restart,"\n"),
		Timeout: 300,
		JobPolicy: 0,
		OkCount: 0,
		Version: "0",
		RpmName: "",
	}
	//log.Println("写入数据库前记录是",js)
	err = s.Db.NewJobStatus(&js)
	if err != nil {
		msg := "任务记录写入数据库异常"
		result.Msg=msg
		log.Println(msg,err.Error())
		panic(msg)
	}
	log.Printf("执行部署 4、jobid %d写入数据库记录成功\n",js.ID)

	// 处理分组
	cs:=ClientGroupByPolicy(rc,0)
	var rpms  utils.Rpms
	// 调整为列表形式的命令，执行任务
	go s.Deploy3(cs,js.ID,0,300,restart,rpms,service)

	result.Data=instances
	result.Code=200
}
